package proc;
import java.io.File;
import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

/**
 * Initializes and sets up the logger for errors and information messages. 
 * Reformats errors according to whether they are error or info level messages.
 * @author Dragon Slayer
 */
public class BasicLogSetup implements LogSetup {	
	private Logger LOG;
	
	/**
	 * Description: Stores a reference to the log.
	 * @requires true
	 * @alters N/A
	 * @ensures true
	 * @param log - to keep track of all errors and information messages
	 */
	public BasicLogSetup(Logger log){
		LOG = log;
	}
		
	/* (non-Javadoc)
	 * @see proc.LogSetup#initializeToErr(java.lang.String)
	 */
	@Override
	public Logger initializeToErr(String logName){
			LOG = Logger.getLogger(logName);
			LOG.setUseParentHandlers(false);
			ConsoleHandler errHandler = new ConsoleHandler();
			errHandler.setFormatter(new ErrorFormatter());
			errHandler.setLevel(Level.SEVERE);
			LOG.addHandler(errHandler);
			return LOG;

	}
	
	/* (non-Javadoc)
	 * @see proc.LogSetup#setInfoLog(java.io.File)
	 */
	@Override
	public boolean setReportLog(File logDest) {//Set up info log to report file
		boolean success = true;
		try {
			FileHandler infoHandler = new FileHandler(logDest.toString());
			infoHandler.setLevel(Level.INFO);
			infoHandler.setFormatter(new InfoFormatter());
			LOG.addHandler(infoHandler);
			
		} catch (SecurityException e) {
			success = false;
			LOG.severe("unable to open " + logDest.toString());
		} catch (IOException e) {
			LOG.severe("008: IO error with " + logDest.toString());//TODO
			success = false;
		}
		return success;
	}
	
	/* (non-Javadoc)
	 * @see proc.LogSetup#closeLog()
	 */
	@Override
	public void closeLog(){
		Handler[] allHandlers = LOG.getHandlers();
		for(int i=0;i<allHandlers.length;i++){
			allHandlers[i].close();
		}
	}
	
	/**
	 * See Programmer's guide for details.
	 * @author Dragon Slayer
	 */
	private class ErrorFormatter extends Formatter{

		@Override
		public String format(LogRecord rec) {
			
			return ("Error_Code " + rec.getMessage()+"\n");
		}
	}	
	
	/**
	 * See Programmer's guide for details.
	 * @author Dragon Slayer
	 */
	private class InfoFormatter extends Formatter{
		
		@Override
		public String format(LogRecord rec) {
			String prefix;
			if(rec.getLevel()==Level.INFO){
				prefix = "REPORT:\t";
			}else{
				prefix = "Error_Code ";
			}
			return (prefix + rec.getMessage()+"\n");
		}
	}

}
